<template>
  <div class="app-container">
    <el-tabs type="border-card" v-if="convertBuiness===false" >
      <el-tab-pane label="客户相关">
    <el-row>
      <el-col span="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="60px">
          <el-form-item label="企业名称" prop="contacts">
            <el-input style="width: 130px" v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable
                      @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="证书名称" prop="name">
            <el-input width="100px" v-model="queryParams.name" placeholder="请输入证书名称" clearable
                      @keyup.enter.native="handleQuery" style="width: 130px" />
          </el-form-item>
          <el-form-item label="预警时间" prop="AbutmentTime">
            <el-date-picker clearable v-model="queryParams.AbutmentTime" type="datetime"
                            value-format="yyyy-MM-dd HH:mm" placeholder="请选择预警时间" style="width: 150px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="服务机构" prop="serviceAgency">
            <el-select v-model="queryParams.selectHonor" placeholder="请选择服务机构" style="width: 150px">
              <el-option v-for="(option, index) in dynamicOptions" :key="index" :label="option.label" :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
<!--            <el-button-->
<!--              type="info"-->
<!--              plain-->
<!--              icon="el-icon-upload2"-->
<!--              size="mini"-->
<!--              @click="handleImport"-->
<!--            >导入</el-button>-->
          </el-form-item>

<!--          <el-form-item label="证书类别" prop="type">-->
<!--            <el-select v-model="queryParams.type" placeholder="请选择证书类别" >-->
<!--              <el-option v-for="dict in dict.type.certificate_type" :key="dict.value" :label="dict.label"-->
<!--                         :value="dict.value"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <div class="search-row manager-row">
            <el-form-item label="证书类别" prop="type">
              <div class="manager-tags">
      <span
        v-for="manager in certificateTypeOptions"
        :key="manager.dictValue"
        :class="['manager-tag', queryParams.type === manager.dictValue ? 'active' : '']"
        @click="handleManagerSelect(manager)"
      >
        {{ manager.dictLabel }}
      </span>
              </div>
            </el-form-item>
          </div>
        </el-form>

<!--        <el-row :gutter="10" class="mb8">-->
<!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
        <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
        <el-table :cell-style="{ padding: '0px' }" height="450" border v-loading="loading" :data="managementList"
                  @selection-change="handleSelectionChange" highlight-current-row :row-style="changeColor"  :class="{ 'no-multiple': markAs != null }"  :header-cell-style="{'text-align':'center'}">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="状态" align="center" prop="status" width="50">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.honer_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="operateTime" width="85" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="证书类别" align="center" prop="type" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.certificate_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="企业名称" align="left" prop="enterpriseName" :show-overflow-tooltip="true"  width="180">
            <template slot-scope="scope">
              <a
                @click="handleToEnterprise(scope.row)"
                class="hyperlink"
                style="color: #46a6ff"
              >
                {{ scope.row.enterpriseName }}
              </a>
            </template>
          </el-table-column>
          <el-table-column label="证书名称" align="left" prop="name" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="发证时间" align="center" prop="entryTime" width="85" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="到期时间" align="center" prop="issuanceTime" width="85" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.issuanceTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="有效期" align="center" prop="issuanceTime" width="60" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{  calculateRemainingYears(scope.row.issuanceTime, scope.row.entryTime) }}年</span>
            </template>
          </el-table-column>
          <el-table-column label="预警时间" align="center" prop="abutmentTime" width="85" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.abutmentTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="第一年监审时间" align="center" prop="firstExamineTime" width="110" :show-overflow-tooltip="true">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ parseTime(scope.row.firstExamineTime, '{y}-{m}-{d}') }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="第二年监审时间" align="center" prop="secondExamineTime" width="110" :show-overflow-tooltip="true">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ parseTime(scope.row.secondExamineTime, '{y}-{m}-{d}') }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="换证时间" align="center" prop="renewalTime" width="100" :show-overflow-tooltip="true">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{ parseTime(scope.row.renewalTime, '{y}-{m}-{d}') }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="预警内容" align="left" prop="oneExamineStage" :show-overflow-tooltip="true" width="140"/>
          <el-table-column label="发证机构" align="center" prop="certificateInstitution" :show-overflow-tooltip="true" width="90"/>
          <el-table-column label="服务机构" align="left" prop="isHuantong" :show-overflow-tooltip="true" />
          <el-table-column label="证书编号" align="center" prop="certificateNo" :show-overflow-tooltip="true" />
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100" >-->
<!--            <template slot-scope="scope">-->
<!--&lt;!&ndash;              :disabled="!shouldShowBusinessButton(scope.row.abutmentTime,scope.row.enterpriseId)"&ndash;&gt;-->
<!--              <el-button  @click="convertBusiness(scope.row)" size="mini" type="text" icon="el-icon-s-opportunity"></el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <!-- 内部文本-->
      </el-col>
    </el-row>
      </el-tab-pane>
      <el-tab-pane label="供应商相关">
  <collabo @show="showBuiness"></collabo>
      </el-tab-pane>
      <el-tab-pane label="平台相关">
        <platform @show="showBuiness"></platform>
      </el-tab-pane>
    </el-tabs>


    <!--   荣誉资质 附件展示对话框-->
    <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body v-if="openFileList">
      <UploadFile :upload-id="uploadId" :business-code="uploadCode"></UploadFile>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <div v-if="convertBuiness">
      <Operate @change="closeEle" :opt="edit" :uuid="uuid" :isClick="isClick" :enterprise-name="enterpriseName" :enterprise-id="enterpriseId"></Operate>
    </div>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { listManagement, getManagement, delManagement, addManagement, updateManagement, treeHonor, reviceHonor,listManagementByEnter } from "@/api/honor/management";
import { getToken } from '@/utils/auth'
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/enterprise/info";
import BusinessInfo from "../enterprise/info/index.vue";
import {getDicts} from "@/api/system/dict/data";
import dia from "../enterprise/seas/dialog.vue";
import FileView from "@/components/FileView/index"
import MainType from "@/components/MainType/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listType } from "@/api/maintype/type";
import UploadFile from "../upload/index.vue";
import Collabo from "./collabo.vue";
import Operate from "../enterprise/businessinfo/operate.vue";
import Platform from "./platform.vue";
export default {
  name: "honorSelect",
  components: {Platform, Operate, Collabo, UploadFile, dia, BusinessInfo, FileView, MainType, Treeselect },
  dicts: ['certificate_type', 'certificate_level', 'honer_status', 'honor_urlname'],
  props: {
    isShow: {
      type: String,
      default: ""
    },
    isOpen: {
      type: Boolean,
      default: false
    },
    orgId: {
      type: String,
      default: null
    }
  },

  data() {

    return {
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      //主分类
      typeCode: 'honor',
      typeCodeResume: 'honor_resume',
      uploadCode: 'honor',
      certificateTypeOptions:[],
      showUpload: false,
      typeSelectHonor: 0,
      enterpriseName:null,//转商机提供的企业名称
      enterpriseId: null,
      // 遮罩层
      loading: true,
      ImgDig: false,
      dialogImageUrl: null,
      // 选中数组
      ids: [],
      // 证书类型选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      dynamicOptions: [],
      //附件预览
      dialogVisible: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 荣誉资质履历表格数据
      resumeList: [],
      // 荣誉资质信息表格数据
      managementList: [],
      // 弹出层标题
      title: "",
      edit: 'add',
      uuid: "",
      //主分类
      options: null,
      //主分类:履历
      optionsResume: null,
      // 是否显示弹出层
      open: false,
      show: false,
      openUser: false,
      //父传子的履历附件标志位
      typeSelect: 0,
      //当前履历总数
      totalResume: 0,
      // 查询参数
      queryParams: {
        name: null,
        type: null,
        customerId: null,
        startTime:null,
        endTime:null,
        pageNum: 1,
        pageSize: 15,
        classificationId: null,
        organizationId: null,
        enterpriseName: null,
        AbutmentTime:null,
        selectHonor:null
      },
      //查询条件，履历
      queryResume: {
        pageNum: 1,
        pageSize: 15,
        honorId: null,
        classificationId: null
      },
      //导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        newMarkAs: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/Honor/management/importData",
      },
      //履历id
      resumeId: null,

      //传递给子类的表单数据
      formResume: {},
      //新增履历弹框
      openResume: false,
      // 表单参数
      form: {},
      //附件对话框
      openFileList: false,
      resumeFileList: false,
      uploadId: null,
      //控制修改和新增
      addSign: 0,
      //履历传递序号
      index: null,
      //履历对话框
      resumeOpen: false,
      //新增还是删除：履历
      resumeSign: 0,
      businessCode: 'resume',
      enterpriseList: [],
      convertBuiness:false,
      isClick: true,
    };

  },
  created() {
    this.dynamicOptions=[
      { label: this.$store.state.user.info.orgName, value: '0' },
      { label: '全部', value: '1' }
    ];
    this.getList();
    this.getEnterInfoList();
    this.listType();
    this.getDicts();
  },
  //监听子组件弹框的boolean值,用于关闭弹窗后，数据重新加载
  watch: {
    openResume: function (newValue, oldValue) {
      // 在someValue发生变化时执行的操作
      console.log('someValue changed:', newValue);
      // 调用您想要执行的方法
      this.getResumeList();
    },
    orgId: function (newValue, oldValue) {
      this.queryParams.organizationId = newValue
      this.getList();
    },
  },
  methods: {
    //获取树节点数据
    listType() {
      listType({ typeCode: 'honor' }).then(res => {
        this.options = res.data;
      })
    },
    calculateRemainingYears(issuanceTime, entryTime) {
      const startDate = new Date(entryTime);
      const endDate = new Date(issuanceTime);
      const yearsDiff = endDate.getFullYear() - startDate.getFullYear();
      if (yearsDiff < 1) {
        return 1; // 不满一年返回一年
      }
      return yearsDiff; // 返回年数差值
    },
    //文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    //查询荣誉资质所有类型
    getDicts() {
      getDicts('certificate_type').then(res => {
        this.certificateTypeOptions = res.data;
        //再插入一个
        this.certificateTypeOptions.unshift({
          dictLabel:"无",
          dictValue:-1
        });
      });
    },
    handleToEnterprise(row) {
      this.$router.push(
        "/enterprise/enterpriseinfo?enterpriseName=" + row.enterpriseName
      );
    },
    handleManagerSelect(manager) {
      if (this.queryParams.type === manager.dictValue) {
        this.queryParams.type = null; // 再次点击取消选择
      } else {
        this.queryParams.type = manager.dictValue;
      }
      this.handleQuery(); // 触发搜索
    },
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    showBuiness(){
      this.convertBuiness=true;
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download('/Honor/management/export', {
    //     ...this.queryParams
    //   }, `荣誉资质商机_${new Date().getTime()}.xlsx`)
    // },
    //转商机
    convertBusiness(row) {
      if (this.$store.state.user.info.companyType==='2'){
        this.$router.push({ path: "/activityinfo/demand", query: { isTrue: true } });
      }else {
        this.uuid = this.guid();
        this.edit = "add";
        this.isClick = true;
        this.convertBuiness = true;
        this.enterpriseName=row.enterpriseName;
        this.enterpriseId=row.customerId;
      }
    },
    closeEle() {
      this.convertBuiness = false;
    },
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    shouldShowBusinessButton(abutmentTime) {
      const currentTime = new Date();
      const warningTime = new Date(abutmentTime);
      const threeMonths = 3 * 30 * 24 * 60 * 60 * 1000; // 3 months in milliseconds
      return (warningTime - currentTime) <= threeMonths;
    },
    changeColor({ row }) {
      const currentDate = new Date();
      const selectedDate = new Date(row.abutmentTime);
      // 计算毫秒级的时间差
      const timeDifference = selectedDate - currentDate;
      // 将毫秒转换为天数
      const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
      // 如果时间差小于3个月（约90天），返回红色，否则返回空字符串
      if (daysDifference < 90) {
        return {
          color: "orange",
          height: '30px' // 这个return的就是样式 可以是color 也可以是backgroundColor
        }
      } else {
        return {
          height: '30px' // 这个return的就是样式 可以是color 也可以是backgroundColor
        }
      }
    },
    /** 查询荣誉资质信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.organizationId = this.orgId;
      console.log(this.queryParams)
      listManagementByEnter(this.queryParams).then(response => {
        this.managementList = response.rows;
        console.log(this.managementList)
        this.total = response.total;
        this.loading = false;
      });
    },
    formatEnterpriseNo(number){
      return `HK${number.toString().padStart(4, '0')}`;
    },
    getWarningColor(abutmentTime) {
      const currentDate = new Date();
      const selectedDate = new Date(abutmentTime);
      // 计算毫秒级的时间差
      const timeDifference = selectedDate - currentDate;
      // 将毫秒转换为天数
      const daysDifference = timeDifference / (1000 * 60 * 60 * 24);
      // 如果时间差小于3个月（约90天），返回红色，否则返回空字符串
      return daysDifference < 90 ? "red" : "";
    },
    //履历对话框
    handleLvli(row) {
      this.reset();
      const id = row.id || this.ids
      this.queryResume.honorId = row.id;
      this.resumeId = row.id;
      this.getResumeList();
      this.resumeOpen = true;
    },
    handleLvRevice(row) {
      this.$confirm("是否接收该荣誉资质证书？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          reviceHonor(row.id).then(res => {
            if (res.code === 200) {
              this.$message.success("接收成功");
              this.getList();
            } else {
              this.$message.error("接收失败");
              this.getList();
            }
          })
        })
    },
    handleClick(url) {
      if (!url.startsWith('http://') && !url.startsWith('https://')) {
        // 如果没有协议，添加默认的http://协议
        url = 'http://' + url;
      } window.open(url, '_blank');
    },
    //取消履历
    cancelResume() {
      this.openResume = false;
      this.show = false;
      this.resetResume();
    },
    closeDig() {
      this.openResume = false;
      this.show = false;
      this.resetResume();
    },
    resetResume() {
      this.formResume = {
        id: null,
        honorId: null,
        concat: null,
        honorTime: null,
        projectId: null,
        dutyPerson: null,
        certificateInstitution: null,
        serviceInstitu: null,
        remark: null,
        uploadFile: null
      };
    },
    handleExceed(files, fileList) {
      this.$message.warning("只允许上传一个文件");
    },
    beforeUpload(file) {
      let size10M = file.size / 1024 / 1024 < 20
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过 20MB!');
        return false
      }
    },
    //企业信息查询
    getEnterInfoList() {
      listInfo().then(res => {
        this.enterpriseList = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.showUpload = false;
      this.reset();
    },
    enterprise() {
      this.openUser = true;
      this.title = '选择';
    },
    close() {
      this.openUser = false
    },
    selectEnterprise(data) {
      this.form.customerId = data.enterpriseId
      this.form.enterpriseName = data.enterpriseName
      console.log(this.form)
      this.close()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        name: null,
        certificateNo: null,
        serviceInstitu: null,
        issuanceTime: null,
        effectiveTime: null,
        abutmentTime: null,
        attachment: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        enterpriseName: null,
        customerId: null,
        operateTime: null,
        list: [],
        fileList: [],
        createId: null,
        entryTime: null,
        uploadFile: null,
        fileUrl: null,
        luRu: null,
        receive: null,
        urlName: null,
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //拿到服务器返回的数据
    handle_success(res) {
      this.form.list.push(res);
      console.log(this.form.list)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        name: null,
        type: '',
        level: null,
        pageNum: 1,
        pageSize: 15,
      };
      this.handleQuery();
    },
    //序号展示
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    handlePictureCardPreviewResume(id) {
      this.uploadId = id;
      this.resumeFileList = true;
    },
    handlePictureCardPreview(id, code) {
      this.uploadId = id;
      this.UploadCode = code;
      this.openFileList = true;
    },
  }
};
</script>
<style scoped>
.warning-color {
  color: red;
  /* 设置预警条件下的所需样式 */
}

.warning-row {
  background-color: orange;
}
.manager-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .manager-tag {
    padding: 4px 12px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s;

    &:hover {
      border-color: #409EFF;
      color: #409EFF;
    }

    &.active {
      background-color: #409EFF;
      border-color: #409EFF;
      color: #fff;
    }
  }
}
</style>
